package com.fjzn.detect.core.utils.sign;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;

import java.util.*;

/**
 *
 * api访问接口签名工具
 *
 * @author yzh
 * @since 2021年04月25日16:20:27
 */
public class SignUtils {


    public static String sign(String content){
        Digester digester = new Digester(DigestAlgorithm.SHA512);
        return digester.digestHex(content);
    }

    public static boolean verify(String sign,String data){
        Digester digester = new Digester(DigestAlgorithm.SHA512);
        return digester.digestHex(data).compareTo(sign) == 0;
    }

    public static String sign(Map<String,Object> content){
        return sign(sortParam(content));
    }

    public static boolean verify(String sign,Map<String,Object> content){
        return verify(sign,sortParam(content));
    }

    public static String sortParam(Map<String,Object> content){
        Map<String ,Object > map = new TreeMap<String,Object>(content);
        StringBuilder sb = new StringBuilder();
        map.forEach((key,val)->{
            if(Objects.nonNull(val)){
                sb.append(key).append("=").append(val).append("&");
            }
        });
        return sb.substring(0,sb.length()-1).toString();
    }

    public static void main(String[] args){

        Map<String,Object> map = new HashMap<>();
        map.put("url","/app/api/rsa/config");
        map.put("x-request-id","e4be7db0-d9cb-454b-bb2e-256031ee61d3");
        map.put("x-time","1610099478459");
        map.put("x-lang","zh");

        System.err.println(sign(map));


        String ct = "hellowor";
        String sign = "3da00c570ca3160fdb7b39838d5f50bd3240e8ac127ceaed13e733915f34209d6e7875b40723a94108f138f1b34f9d69bb171ea6d9baeaefa7dbd4c9a03a1812";
        System.out.println(sign(ct));
        System.out.println(verify(sign,ct));
        StringBuilder sb = new StringBuilder();
        sb.append(Arrays.asList(1,2));
        System.out.println(sb.toString());
    }
}
